/**
 * File Created: 2018-01-19 10:23
 * Author: xxq (you@you.you)
 * __________________________________________________
 * Last Modified: 2018-01-19 14:39:33
 * Modified By: xxq (you@you.you>)
 * __________________________________________________
 * Copyright - 2018 xnb, xnb
 */
const baseUrl = 'http://uadmin.51xnb.cn/';
const hash = key => {
    let hash = 0;
    for (var i = 0; i < key.length; i++) {
        hash = (1313 * hash + key.charCodeAt(i)) % 10000000000;
    }
    return hash;
};

const requiredParams= () => {
    let param = {},
        _sid = localStorage.getItem("_sid");
    if (_sid == undefined) {
        _sid = "WS" + new Date().getTime();
        localStorage.setItem("_sid", _sid);
    } else {
        let serverKey = localStorage.getItem("_serverKey");
        if (serverKey==undefined) {
            serverKey = "";
        }
        param._t = new Date().getTime() + "";
        const value = `${_sid}&${serverKey}&${param._t}`;
        param._sign = hash(value);
    }
    param._sid = _sid;

    return param;
};

const fetchData = (url, param, cb) => {
    let params = Object.assign(requiredParams(), param)
    let formData = new FormData();
    console.log(params)
    Object.keys(params).map(key => {
        formData.append(key, params[key])
    });
    (async () => {
        try{
            let res = await fetch(baseUrl + url, { 
                method: 'POST', 
                // headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, 
                body: formData
            }),
                data = await res.json(); 
            cb(data);
            
            if(data.code === 200){
                // cb(data)
                // return new Promise( (resolve, reject) => {
                    
                // })
            }else if (data.code == 401) {
                // 会话异常; TODO: 该情况下最好跳转到进入登录页或者首页
                localStorage.removeItem("_sid");
                localStorage.removeItem("_serverKey");
            } else if (data.code == 402) {
                // location.href= base.localhostUrl + 'login.html'; // TODO: 需要用户登录，强制跳转到登录页面，或者弹出一个带进入登录页面链接的提示框
            } else if(data.code && data.code !== 200){ 
                var msg = data.msg? data.msg : "服务端处理异常"
                alert(msg) // 提示异常信息
            }
        }catch(e){
            console.log(e)
        }
    })()
}
export { fetchData, requiredParams}